﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DotSpatial.Controls;
using DotSpatial.Data;
using Microsoft.Win32;
using Kitware.VTK;
using Kitware.mummy;

namespace HA.ModFlow.Controls.Windows
{
    /// <summary>
    /// winExportBitmap.xaml 的交互逻辑
    /// </summary>
    public partial class winExportBitmap : Window
    {
        public winExportBitmap(Map map)
        {
            this._map = map;

            //第一步生成预览
            _bitmap = this._map.SnapShot();

            DotSpatial.Data.InRamImageData imageData = new InRamImageData(_bitmap);
            imageData.Projection = DotSpatial.Projections.KnownCoordinateSystems.Geographic.World.WGS1984;

            this._bitmapSource = ConvertBitmapToBitmapSource(_bitmap);


            //取得map对应的比例
            double orgW = (double)this._map.ViewExtents.Width;
            double orgH = (double)this._map.ViewExtents.Height;

            //计算对应的比例
            wToh = orgW / orgH;

            this._bitmapHeight = Convert.ToInt32(this._bitmapWidth / wToh);

            InitializeComponent();

            this.image1.Source = this._bitmapSource;

            this.DataContext = this;
        }

        public winExportBitmap(vtkRenderWindow vtkMap)
        {
            _vtkMap = vtkMap;

            vtkWindowToImageFilter imageFilter = vtkWindowToImageFilter.New();

            imageFilter.SetInput(this._vtkMap);



            imageFilter.SetMagnification(1);

            imageFilter.Update();

            this._bitmap = imageFilter.GetOutput().ToBitmap();

            this._bitmapSource = ConvertBitmapToBitmapSource(_bitmap);


            //取得map对应的比例
            double orgW = (double)this._bitmap.Width;
            double orgH = (double)this._bitmap.Height;

            //计算对应的比例
            wToh = orgW / orgH;

            this._bitmapHeight = Convert.ToInt32(this._bitmapWidth / wToh);

            InitializeComponent();

            this.image1.Source = this._bitmapSource;

            this.DataContext = this;
        }

        Map _map;

        vtkRenderWindow _vtkMap;

        private int _bitmapWidth = 2000;

        public int BitmapWidth
        {
            get { return _bitmapWidth; }
            set
            {
                if (value > 0)
                {
                    _bitmapWidth = value;
                }
            }
            
        }


        private int _bitmapHeight = 2000;

        public int BitmapHeight
        {
            get { return _bitmapHeight; }
            set
            {
                if (value > 0)
                    _bitmapHeight = value;
            }
        }

        System.Drawing.Bitmap _bitmap;

        System.Windows.Media.Imaging.BitmapSource _bitmapSource;

        double wToh;
        
        public static BitmapSource ConvertBitmapToBitmapSource(System.Drawing.Bitmap src)
        {
            IntPtr hBitmap = src.GetHbitmap();
            BitmapSource output = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap,

                                          IntPtr.Zero, Int32Rect.Empty,

                                          BitmapSizeOptions.FromEmptyOptions());

            return output;
        }


        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "保存图像";
            sfd.CheckPathExists = true;
            sfd.OverwritePrompt = true;
            sfd.Filter = "Bitmap File(*.bmp)|*.bmp|" + "Gif File(*.gif)|*.gif|" + "JPEG File(*.jpg)|*.jpg|" + "PNG File(*.png)|*.png";
            if (sfd.ShowDialog().Value)
            {
                //this.WindowState = System.Windows.WindowState.Minimized;
                this.Close();
                try
                {
                    this._bitmap = this.GetPrintBitmap();

                    string filename = sfd.FileName;
                    string format = filename.Remove(0, filename.Length - 3);
                    switch (format)
                    {
                        case "bmp":
                            this._bitmap.Save(sfd.FileName, System.Drawing.Imaging.ImageFormat.Bmp);
                            break;
                        case "jpg":
                            this._bitmap.Save(sfd.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                            break;
                        case "gif":
                            this._bitmap.Save(sfd.FileName, System.Drawing.Imaging.ImageFormat.Gif);
                            break;
                        case "png":
                            this._bitmap.Save(sfd.FileName, System.Drawing.Imaging.ImageFormat.Png);
                            break;
                        default:
                            break;

                    }
                }
                catch
                {
                    _bitmap.Dispose();
                    MessageBox.Show("图像像素设置过大，请重新输入！（5000像素以内较为合适）");
                }
            }
        }

        /// <summary>
        /// 取得当前设置下的高打印性能图形
        /// </summary>
        /// <returns></returns>

        public System.Drawing.Bitmap GetPrintBitmap()
        {
            if (this._map != null)
            {
                System.Drawing.Bitmap newBitmap = new System.Drawing.Bitmap(this._bitmapWidth, this._bitmapHeight);

                //newBitmap.SetResolution(300, 300);

                System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(newBitmap);

                g.Clear(System.Drawing.Color.FromArgb(255, _map.BackColor));

                System.Drawing.Rectangle rec = new System.Drawing.Rectangle(0, 0, (int)this._bitmapWidth, (int)this._bitmapHeight);

                _map.Print(g, rec, _map.ViewExtents);

                g.Dispose();

                return newBitmap;
            }
            else
            {
                vtkWindowToImageFilter imageFilter = vtkWindowToImageFilter.New();

                imageFilter.SetInput(this._vtkMap);

                int radio = _bitmapWidth % _bitmap.Width == 0 ? _bitmapWidth / _bitmap.Width : _bitmapWidth / _bitmap.Width + 1;

                imageFilter.SetMagnification(radio);

                imageFilter.Update();

                _bitmap = imageFilter.GetOutput().ToBitmap();

                this.PicSized();

                return _bitmap;
            }


        }

        private void btnCopy_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this._bitmap = this.GetPrintBitmap();
                System.Windows.Forms.Clipboard.SetImage(this._bitmap);
            }
            catch
            {
                System.Windows.Forms.Clipboard.Clear();
                MessageBox.Show("图像像素设置过大，请重新输入！（5000像素以内较为合适）");
            }
        }

        private void txtWidth_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                this._bitmapHeight = Convert.ToInt32(Convert.ToInt32(this.txtWidth.Text) / this.wToh);
            }
            catch
            {

            }
            this.txtHeight.Text = this._bitmapHeight.ToString();
        }

        private void PicSized()
        {
            int w = _bitmapWidth;
            int h = _bitmapHeight;
            System.Drawing.Bitmap resizedBmp = new System.Drawing.Bitmap(w, h);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(resizedBmp);
            //设置高质量插值法   
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度   
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            //消除锯齿 
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            g.DrawImage(_bitmap, new System.Drawing.Rectangle(0, 0, w, h), new System.Drawing.Rectangle(0, 0, _bitmap.Width, _bitmap.Height), System.Drawing.GraphicsUnit.Pixel);
            _bitmap = resizedBmp;
            g.Dispose();
        }
    }
}
